package edu.sctu.zhoumengxue.day201506.day20150614.serialization;

import java.io.*;
import java.text.MessageFormat;

/**测试对象的序列化和反序列化
 * Created by user12 on 2015/6/14.
 */
public class Main {

    public static void main(String[] args) throws Exception{

        SerializablePerson();//序列化Person对象
        Person p = DeserializePerson();//反序列化Person对象
        System.out.println(MessageFormat.format("name:{0},age:{1},sex:{2}",p.getName(),p.getAge(),p.getSex()));

    }
/*将Person对象储存到D盘的Person.txt文件中，完成序列化*/
    public static void SerializablePerson() throws IOException{
        Person person = new Person();
        person.setName("周梦雪");
        person.setAge(20);
        person.setSex("女");

        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File("D:/Person.txt")));
        out.writeObject(person);
        System.out.println("Person序列化成功!");
        out.close();

    }
/*反序列化Person对象*/
    private static Person DeserializePerson() throws Exception{

        ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File("D:/Person.txt")));
        Person person = (Person) in.readObject();
        System.out.println("Person反序列化对象成功!");
        return person;
    }
}
